package ua.org.plast.mobileApp.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;

/**
 * Created with IntelliJ IDEA.
 * User: Virus1908
 * Date: 18.11.13
 * Time: 21:43
 */
public class ImageUtils {
    public interface OnLoadListener {
        void onLoad();
    }

    private static HashMap<String, Bitmap> sImagePool = new HashMap<String, Bitmap>();
    private HashSet<AsyncTask> mTasks = new HashSet<AsyncTask>();
    private OnLoadListener mOnLoadListener;
    private boolean mAllowListener;

    public void loadBitmapAsync(final String urlString) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected void onPreExecute() {
                mTasks.add(this);
                mAllowListener = false;
            }

            @Override
            protected Void doInBackground(Void... voids) {
                if (sImagePool.get(urlString) != null) {
                    return null;
                }
                URL url = null;
                try {
                    url = new URL(urlString);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    Bitmap myBitmap = BitmapFactory.decodeStream(input);
                    sImagePool.put(urlString, myBitmap);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                mTasks.remove(this);
                if (mAllowListener && mTasks.isEmpty()) {
                    mAllowListener = false;
                    if (mOnLoadListener != null) {
                        mOnLoadListener.onLoad();
                    }
                }
            }
        }.execute();
    }

    public void setOnLoadListener(OnLoadListener listener) {
        mOnLoadListener = listener;
    }

    public void allowLoadListener() {
        mAllowListener = true;
        if (mTasks.isEmpty()) {
            mAllowListener = false;
            if (mOnLoadListener != null) {
                mOnLoadListener.onLoad();
            }
        }
    }

    public static Bitmap getBitmap(String key) {
        return sImagePool.get(key);
    }


}
